# coding=utf-8
from datetime import datetime, timedelta
from django.conf import settings
from django.db.models import Q
from django.utils.safestring import mark_safe
from django.core.mail import send_mail
from django.template import Context, Template
from urllib import basejoin
import persistent_messages
from persistent_messages.models import Message
from mailer import send_html_mail
from mitems.models import Notification


############################################################################

AIRTIME_MESSAGE = Template('Your airtime credit is <span class="strong">{{ airtime }} airtime</span>. '+
                           '<a class="restore_airtime" href="/user/restore_airtime">'+
                           'Click here to add airtime to your account</a>.'
)
EMAIL_MESSAGE = ('<a href="/profile">Update you email address</a>'+
                ' to enable notifications, so you can stay online when you are off 8'
)
MAIL_ADD_MESSAGE = Template('Your item <a href="{{ item.get_absolute_url }}">{{ item.message }}</a>'+
                            ' was published successfully on {% now "H:i A, l F j, Y" %}'
)
FACEBOOK_POSTING = ('Automatic posting to Facebook is turned off. To enable it '
                    '<a href="/profile/">click here</a>')

##############################################################################

EMAIL_FOOTER = u"""

--
* To manage your email settings, go to: %s
* Please add 8minutes to your address list so we won't get lost in spam.

There's something happening everywhere! Break the news on 8minutes.

© 8minutes 2011
""" % basejoin(settings.SITE_URL, 'notifications/')

###############################################################
MY_EMAIL_SUBJECT = 'Your 8minutes Upload Email'

MY_EMAIL_BODY = u"""Now you can submit items straight to your profile via email.
Simply send an email with a photo attachment to: %s

* Item title -> email subject
* Item photo -> add as an attachment
* Item more details (optional) -> email body
* Item category (optional) -> #category-name (for example: #news)
  If not indicated, item will be placed in Personal category.
""" + EMAIL_FOOTER

################################################################

COMMENT_LIKE_SUBJECT = Template('New response for: {{ comment.item }}')

COMMENT_BODY = Template("""
{{ comment.user.get_username }} just posted a response for: {{ comment.item }}

{{ comment.comment }}

Read and reply to responses here: {{ comment.item.get_short_url }}
""" + EMAIL_FOOTER)

LIKE_BODY = Template("""
{{ comment.user.get_username }} just posted a response for: {{ comment.item }}

{{ comment.user.first_name }} Likes your post!

Read and reply to responses here: {{ comment.item.get_short_url }}
""" + EMAIL_FOOTER)

COMMENT_LIKE_WEB = Template('<a href="{{comment.user.get_absolute_url}}">{{comment.user.get_username}}</a> '+
                            'posted a response on your item '+
                            '<a href="{{comment.item.get_absolute_url}}">{{comment.item}}</a>')

#################################################################

FOLLOW_SUBJECT = Template('{{ follower.get_username }} is now following you on 8minutes!')

FOLLOW_BODY = Template("""
{{ follower.get_username }} is now following you on 8minutes!

Following {{ follower.first_name }} back makes it easier to focus on items that matter to you.

To follow {{ follower.first_name }} click here: {{ follower.get_absolute_url }}
""" + EMAIL_FOOTER)

FOLLOW_WEB = Template('<a href="{{ follower.get_absolute_url }}">{{ follower.get_username }}</a> '+
                      'is now following you. Find out more about '+
                      '<a href="{{ follower.get_absolute_url }}">{{ follower.first_name }}</a>')

###################################################################

FOLLOWER_SUBMIT_SUBJECT = Template('{{ user.get_username }} just posted: {{ item }}')

FOLLOWER_SUBMIT_BODY = Template("""
{{ user.get_username }} just posted a new item: {{ item }}  and it has only 8 minutes to live!

To keep this item LIVE by joining the discussion, click here: {{ item.get_short_url }}
""" + EMAIL_FOOTER)

FOLLOWER_SUBMIT_WEB = Template('<a href="{{user.get_absolute_url}}">{{ user.get_username }}</a> '+
                               'just posted: <a href="{{ item.get_absolute_url }}">{{ item }}</a>')

#######################################################################

FOLLOWER_COMMENT_LIKE_SUBJECT = Template('{{ comment.user.get_username }} just responded to:'+
                                         '{{ comment.item }}')

FOLLOWER_COMMENT_BODY = Template("""
{{ comment.user.get_username }} just submitted a response to: {{ comment.item }}

{{ comment.comment }}

To keep this item LIVE by joining the discussion, click here: {{ comment.item.get_short_url }}
""" + EMAIL_FOOTER)

FOLLOWER_LIKE_BODY = Template("""
{{ comment.user.get_username }} just submitted a response to: {{ comment.item }}

{{ comment.user.first_name }} Likes this post!

To keep this item LIVE by joining the discussion, click here: {{ comment.item.get_short_url }}
""" + EMAIL_FOOTER)

FOLLOWER_COMMENT_LIKE_WEB = Template('<a href="{{comment.user.get_absolute_url}}">'+
                                     '{{ comment.user.get_username }}</a> '+
                                     'just posted a response on '+
                                     '<a href="{{ comment.item.get_absolute_url }}">{{ comment.item }}</a>')

###################################################################################

LOGIN_SUBJECT = Template('Welcome to 8minutes, {{ user.first_name }}')

LOGIN_BODY = Template("""
{{ user.first_name }} we're excited to have you on board!

There's something happening everywhere and now you can break the news, any news,
be influential and be informed in a fun and entertaining way.

Getting started:

* Submit the news via the website or directly from your mobile phone via your personal 8minutes email {{user.mobile_email}}
* Comment, share or like the items that interest you to give them more time to stay LIVE: {{popular}}
* Complete your profile and watch the things that matters to you: {{profile}}

Please be sure to click on the feedback link in the footer to let us know what you think, so we can make the best website possible.
""" + EMAIL_FOOTER)

LOGIN_WEB = ('Thank you for taking part in 8minutes beta! '+
             'Please leave your feedback by '+
             '<a onmouseover="UE.Popin.preload();" href="#feedback"'+
             'onclick="UE.Popin.show(); return false;">clicking the feedback link</a> in the footer.')

######################################################################################

SLUMP_IN_2_SUBJECT = 'Your item is going to slump in 2 minutes!'

SLUMP_IN_2_BODY = Template("""
Your item: {{ item }} is going to slump in 2 minutes!

Add airtime to keep it LIVE! here: {{ item.get_short_url }}
""" + EMAIL_FOOTER)

SLUMP_IN_2_WEB = Template('Your item <a href="{{ item.get_absolute_url }}">{{ item }}</a> '+
                          'is going to slump in 2 minutes. Add airtime to keep it LIVE.')

######################################################################################

GOOGLE_INVITE_SUBJECT = Template("{{ user.first_name }} has invited you to join 8minutes")
GOOGLE_INVITE_MESSAGE = Template("""
Hi,

{{ message|safe }}

Join now!
Click the Connect with Facebook button on: {{ site }}

Check out my profile:
{{ user.get_absolute_url }}

- {{ user.first_name }}
""")

#########################################################################################

def notify_web(user, message, level="INFO"):
    """Add notify right to base"""
    Message.objects.create(user=user,
                           message=message,
                           level=getattr(persistent_messages, level, persistent_messages.INFO),
                           expires = datetime.now()+timedelta(
                               seconds=getattr(settings, 'MESSAGE_EXPIRE_TIMEOUT', 10)
                           ),
                           close_timeout=getattr(settings, 'MESSAGE_CLOSE_TIMEOUT', 10000)
    )


def notify_item_mail(item):
    message = MAIL_ADD_MESSAGE.render(Context(dict(item=item)))
    notify_web(item.created_by, mark_safe(message))


def notify_slump_in_2(items):
    notifies = Notification.objects.filter(
        Q(minutes_2_site=True) | Q(minutes_2_email=True),
        user__in=[item.created_by for item in items]
    )
    users_for_notify = dict([(notify.user, notify) for notify in notifies ])
    if not users_for_notify:
        return
    for item in items.iterator():
        if item.created_by in users_for_notify:
            content = Context(dict(item=item))
            if users_for_notify[item.created_by].minutes_2_site:
                message = SLUMP_IN_2_WEB.render(content)
                notify_web(notify.user, mark_safe(message), level='ERROR')
            if users_for_notify[item.created_by].minutes_2_email:
                message = SLUMP_IN_2_BODY.render(content)
                send_mail(SLUMP_IN_2_SUBJECT, message, settings.EMAIL_FROM,
                          [item.created_by.email])


def notify_airtime(user):
    """Airtime notify"""
    try:
        Notification.objects.get(user=user, news_site=True)
    except Notification.DoesNotExist:
        return
    message = AIRTIME_MESSAGE.render(Context(dict(airtime=user.airtime)))
    notify_web(user, mark_safe(message))


def notify_comment(comment, like=False):
    """ Notify item owner for new comments """
    try:
        notify = Notification.objects.get(
            Q(someone_comment_me_site=True) | Q(someone_comment_me_email=True),
            user=comment.item.created_by
        )
    except Notification.DoesNotExist:
        return
    content = Context(dict(comment=comment))
    if notify.someone_comment_me_site:
        message = COMMENT_LIKE_WEB.render(content)
        notify_web(notify.user, mark_safe(message))
    if notify.someone_comment_me_email:
        subject = COMMENT_LIKE_SUBJECT.render(content)
        if not like:
            message = COMMENT_BODY.render(content)
        else:
            message = LIKE_BODY.render(content)
        send_mail(subject, message, settings.EMAIL_FROM,
                  [notify.user.email])


def notify_follow_me(follower, follow):
    """ Notify when follow me"""
    try:
        notify = Notification.objects.get(
            Q(someone_follow_me_site=True) | Q(someone_follow_me_email=True),
            user=follow
        )
    except Notification.DoesNotExist:
        return
    content = Context(dict(follower=follower))
    if notify.someone_follow_me_site:
        message = FOLLOW_WEB.render(content)
        notify_web(notify.user, mark_safe(message))
    if notify.someone_follow_me_email:
        subject =  FOLLOW_SUBJECT.render(content)
        message = FOLLOW_BODY.render(content)
        send_mail(subject, message, settings.EMAIL_FROM, [notify.user.email])


def notify_follow_submit(item):
    """ Notify item owner followers for item submit"""
    notifies = Notification.objects.filter(
        Q(follow_submit_item_site=True) | Q(follow_submit_item_email=True),
        user__in=item.created_by.get_followers()
    )
    if not notifies:
        return
    content = Context(dict(user=item.created_by, item=item))
    for notify in notifies:
        if notify.follow_submit_item_site:
            message = FOLLOWER_SUBMIT_WEB.render(content)
            notify_web(notify.user, mark_safe(message))
        if notify.follow_submit_item_email:
            subject =  FOLLOWER_SUBMIT_SUBJECT.render(content)
            message = FOLLOWER_SUBMIT_BODY.render(content)
            send_mail(subject, message, settings.EMAIL_FROM, [notify.user.email])


def notify_follow_comment(comment, like=False):
    """ Notify item owner followers for new comments"""
    notifies = Notification.objects.filter(
        Q(follow_comment_item_site=True) | Q(follow_comment_item_email=True),
        user__in=comment.user.get_followers()
    )
    if not notifies:
        return
    content = Context(dict(comment=comment))
    for notify in notifies:
        if notify.follow_comment_item_site:
            message = FOLLOWER_COMMENT_LIKE_WEB.render(content)
            notify_web(notify.user, mark_safe(message))
        if notify.follow_comment_item_email:
            subject = FOLLOWER_COMMENT_LIKE_SUBJECT.render(content)
            if not like:
                message = FOLLOWER_COMMENT_BODY.render(content)
            else:
                message = FOLLOWER_LIKE_BODY.render(content)
            send_mail(subject, message, settings.EMAIL_FROM, [notify.user.email])


def notify_login(user):
    """ First login notify"""
    try:
        notify = Notification.objects.get(Q(news_site=True) | Q(news_email=True), user=user)
    except Notification.DoesNotExist:
        return
    content = Context(dict(user=user,
                           site=settings.SITE_URL,
                           popular=basejoin(settings.SITE_URL, 'live/popular/'),
                           profile=basejoin(settings.SITE_URL, 'profile/'))
    )
    if notify.news_site:
        notify_web(user, mark_safe(FACEBOOK_POSTING))
        notify_web(user, mark_safe(LOGIN_WEB))
    if notify.news_email:
        subject = LOGIN_SUBJECT.render(content)
        message = LOGIN_BODY.render(content)
        send_mail(subject, message, settings.EMAIL_FROM, [user.email])


def google_invite_mail(user, message, emails):
    """ Google invite mail """
    content = Context(dict(user=user, message=message, site=settings.SITE_URL))
    subject = GOOGLE_INVITE_SUBJECT.render(content)
    message = GOOGLE_INVITE_MESSAGE.render(content)
    send_mail(subject, message, settings.EMAIL_FROM, emails)


def google_invite_web(user, count):
    """ Google invite web notify """
    try:
        Notification.objects.get(news_site=True, user=user)
    except Notification.DoesNotExist:
        return
    message = ("Email was sent successfully to 1 contact" if count == 1 else
               "Emails were sent successfully to %s contacts" % count)
    notify_web(user, mark_safe(message))